package com.cuijian.demo.controller;

import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.cuijian.demo.common.JsonResult;
import com.cuijian.demo.model.User;
import com.cuijian.demo.util.PasswordUtil;
import com.cuijian.demo.util.TokenManager;
import com.cuijian.demo.util.JsonUtil;
import com.cuijian.demo.dto.LoginRequest;
import com.cuijian.demo.dto.RegisterRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Path("/api/auth")
public class AuthController extends Controller {

    /**
     * 用户登录 - 支持JSON和表单格式
     */
    public void login() {
        String username;
        String password;

        // 检查是否为JSON请求
        if (JsonUtil.isJsonRequest(this)) {
            LoginRequest loginRequest = JsonUtil.getJsonData(this, LoginRequest.class);
            if (loginRequest == null) {
                renderJson(JsonResult.error("请求数据不能为空").toMap());
                return;
            }
            username = loginRequest.getUsername();
            password = loginRequest.getPassword();
        } else {
            // 表单格式
            username = get("username");
            password = get("password");
        }

        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            renderJson(JsonResult.error("用户名不能为空").toMap());
            return;
        }

        if (password == null || password.trim().isEmpty()) {
            renderJson(JsonResult.error("密码不能为空").toMap());
            return;
        }

        try {
            // 查找用户
            User user = User.dao.findByUsername(username);
            if (user == null) {
                renderJson(JsonResult.error("用户名或密码错误").toMap());
                return;
            }

            // 验证密码
            if (!PasswordUtil.verify(password, user.getPassword())) {
                renderJson(JsonResult.error("用户名或密码错误").toMap());
                return;
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                renderJson(JsonResult.error("账号已被禁用，请联系管理员").toMap());
                return;
            }

            // 更新登录信息
            String clientIp = getClientIp();
            user.updateLoginInfo(user.getId(), clientIp);

            // 生成token
            String token = TokenManager.createToken(user.getId(), user.getUsername());

            // 返回用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("phone", user.getPhone());
            userInfo.put("realName", user.getRealName());
            userInfo.put("avatar", user.getAvatar());
            userInfo.put("lastLoginTime", user.getDate("last_login_time"));

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("userInfo", userInfo);

            renderJson(JsonResult.success("登录成功", result).toMap());

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("登录失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 用户注册 - 支持JSON和表单格式
     */
    public void register() {
        String username;
        String password;
        String email;
        String phone;
        String realName;

        // 检查是否为JSON请求
        if (JsonUtil.isJsonRequest(this)) {
            RegisterRequest registerRequest = JsonUtil.getJsonData(this, RegisterRequest.class);
            if (registerRequest == null) {
                renderJson(JsonResult.error("请求数据不能为空").toMap());
                return;
            }
            username = registerRequest.getUsername();
            password = registerRequest.getPassword();
            email = registerRequest.getEmail();
            phone = registerRequest.getPhone();
            realName = registerRequest.getRealName();
        } else {
            // 表单格式
            username = get("username");
            password = get("password");
            email = get("email");
            phone = get("phone");
            realName = get("realName");
        }

        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            renderJson(JsonResult.error("用户名不能为空").toMap());
            return;
        }

        if (password == null || password.trim().isEmpty()) {
            renderJson(JsonResult.error("密码不能为空").toMap());
            return;
        }

        if (email == null || email.trim().isEmpty()) {
            renderJson(JsonResult.error("邮箱不能为空").toMap());
            return;
        }

        try {
            // 检查用户名是否已存在
            if (User.dao.isUsernameExists(username)) {
                renderJson(JsonResult.error("用户名已存在").toMap());
                return;
            }

            // 检查邮箱是否已存在
            if (User.dao.isEmailExists(email)) {
                renderJson(JsonResult.error("邮箱已被注册").toMap());
                return;
            }

            // 创建新用户
            User user = new User();
            user.set("username", username);
            user.set("password", PasswordUtil.md5(password)); // 密码加密存储
            user.set("email", email);
            user.set("phone", phone);
            user.set("real_name", realName);
            user.set("status", 1);
            user.set("create_time", new Date());
            user.set("update_time", new Date());

            boolean success = user.save();
            if (success) {
                // 发送用户注册消息（如果启用了RocketMQ）
                try {
                    com.cuijian.demo.service.RocketMQProducerService producerService =
                            new com.cuijian.demo.service.RocketMQProducerService();
                    producerService.sendUserRegisterMessage(
                            user.getLong("id"),
                            username,
                            email
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                    // 消息发送失败不影响主流程
                }

                renderJson(JsonResult.success("注册成功").toMap());
            } else {
                renderJson(JsonResult.error("注册失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("注册失败: " + e.getMessage()).toMap());
        }
    }

    // 其他方法保持不变...
    public void logout() {
        String token = getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            TokenManager.removeToken(token);
        }
        renderJson(JsonResult.success("登出成功").toMap());
    }

    public void currentUser() {
        String token = getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            TokenManager.TokenInfo tokenInfo = TokenManager.getTokenInfo(token);

            if (tokenInfo != null && !tokenInfo.isExpired()) {
                User user = User.dao.findById(tokenInfo.getUserId());
                if (user != null && user.getStatus() == 1) {
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("id", user.getId());
                    userInfo.put("username", user.getUsername());
                    userInfo.put("email", user.getEmail());
                    userInfo.put("phone", user.getPhone());
                    userInfo.put("realName", user.getRealName());
                    userInfo.put("avatar", user.getAvatar());
                    userInfo.put("lastLoginTime", user.getDate("last_login_time"));
                    userInfo.put("createTime", user.getCreateTime());

                    renderJson(JsonResult.success(userInfo).toMap());
                    return;
                }
            }
        }

        renderJson(JsonResult.error("未登录或token已过期").toMap());
    }

    private String getClientIp() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}